package com.ymttest.database.mongo;

import java.util.ArrayList;

import com.ymt.core.tool.FormatUtil;
import com.ymt.database.MongoDBDriver;
import com.ymttest.utils.EnvSetup;

/**
 * PhoneBlackListWapper
 * 
 * @author chenjiazhu
 *
 */
public class PhoneBlackListWapper {
	MongoDBDriver mdd;

	public PhoneBlackListWapper() throws Exception {
		mdd = new MongoDBDriver(EnvSetup.getSystemUrl("set4_mongoip"), Integer.valueOf(EnvSetup
				.getSystemUrl("set4_mongoport")), "SmsProxyDB");
		mdd.selectCollection("PhoneBlackList");
	}

	/**
	 * 用appId,phone查询整条记录
	 * 
	 * @param appid
	 * @return PhoneBlackListBean
	 * @throws Exception
	 */
	public PhoneBlackListBean getCollectionByAppIdAndPhone(String appId, String phone) throws Exception {
		String re = null;
		PhoneBlackListBean bean = null;
		ArrayList<String> list = mdd.selectPartLimit("{\"AppId\":" + appId + ",\"Phone\":"+phone+"}", 1);
		
		try {
			if (list.size() > 0) {
				re = list.get(0);
				bean = (PhoneBlackListBean) FormatUtil.GSONToObject(re, PhoneBlackListBean.class);
				return bean;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 获取第一条记录
	 * 
	 * @return PhoneBlackListBean
	 * @throws Exception
	 */
	public PhoneBlackListBean getTop1Collection() throws Exception {
		String re = null;
		PhoneBlackListBean bean = null;
		ArrayList<String> list = mdd.selectLimit(1);
		
		try {
			if (list.size() > 0) {
				re = list.get(0);
				bean = (PhoneBlackListBean) FormatUtil.GSONToObject(re, PhoneBlackListBean.class);
				return bean;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 增加一条黑名单记录
	 * 
	 * @return PhoneBlackListBean
	 * @throws Exception
	 */
	public void updateCollection(String AppId, String ApiName,String Phone,String StartTime, String EndTime) throws Exception {
		String re = null;
		PhoneBlackListBean bean = null;
		
		String findJson="{\"AppId\":\""+AppId+"\", \"Phone\" : \""+Phone+"\"}";	
		String updateJson="{\"_id\":\""+AppId+"-"+ApiName+"-"+Phone+"\",\"AppId\":\""+AppId+"\",\"ApiName\":\""+ApiName+"\",\"Phone\":\""+Phone+"\",\"StartTime\":{$date:\""+StartTime+"\"},\"EndTime\":{$date:\""+EndTime+"\"}}";
		
		mdd.update(findJson, updateJson);
	}
}
